#include "svn_cmd.h"
#include <wx/utils.h>
#include <wx/sstream.h>
#include <wx/xml/xml.h>
#include <wx/log.h>

using namespace svn;

Command::Command(const wxString& sSvnCmd)
: m_bInstalled(false)
{
	SetSvnCommand(sSvnCmd);
}

bool Command::SetSvnCommand(const wxString& sSvnCmd)
{
	m_sSvnCmd = sSvnCmd;
	m_bInstalled = Execute(wxT("--version"));
	return m_bInstalled;
}

bool Command::Execute(const wxString& sArgs, wxString* pOutput) const
{
	wxString sCmd;
	sCmd << m_sSvnCmd << wxT(' ') << sArgs;
	wxArrayString outputArray;
	if ( ::wxExecute(sCmd, outputArray, wxEXEC_SYNC) == -1) {
		return false;
	}

	wxLogMessage(wxT("VersionManager : %s : %s..."), sCmd.c_str(), outputArray[0].c_str());

	if (pOutput) {
		pOutput->clear();
		for (wxArrayString::const_iterator itRow = outputArray.begin(); itRow != outputArray.end(); ++itRow) {
			*pOutput << *itRow << wxT('\n');
		}
	}
	return true;
}

bool Command::GetRevision(long& rRevision, const wxString& sPath)
{
	if (!m_bInstalled) {
		return false;
	}

	wxString xmlRevisionInfos;
	if (Execute(wxT("info --xml"), &xmlRevisionInfos) == false) {
		return false;
	}

	wxStringInputStream stream(xmlRevisionInfos);
	wxXmlDocument xmlDoc;
	if (xmlDoc.Load(stream) == false) {
		return false;
	}

	wxXmlNode* pRoot = xmlDoc.GetRoot();
	if (!pRoot || (pRoot->GetName() != wxT("info"))) {
		return false;
	}

	bool bFound = false;
	wxXmlNode* pChild = pRoot->GetChildren();
	while (pChild && !bFound) {
		if (pChild->GetName() == wxT("entry")) {
			wxString sRevision;
			if (pChild->GetPropVal(wxT("revision"), &sRevision)) {
				bFound = sRevision.ToLong(&rRevision);
			}
		}
		pChild = pChild->GetNext();
	}
	return bFound;
}
